package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author wangqian
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存SPU商品基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2、保存描述图片 pms_spu_info_desc
        List<String> descrip = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", descrip));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3、保存图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);
        //4、保存规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            if (attrEntity != null) {
                attrValueEntity.setAttrName(attrEntity.getAttrName());
            }
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(attrValueEntities);
        //补充 保存积分信息 sms_spu_bounds

        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() == 0) {

        } else {
            log.error("远程保存SPU满减信息错误");
        }
        //5、保存当前SKU对应的所有信息
        List<Skus> skuses = vo.getSkus();

        if (skuses != null && skuses.size() > 0) {
            skuses.forEach(sku -> {

                //此处先进行图片搜索，是为了保存默认图片，图片集数据为1时，就是默认图片
                String defaultImage = null;
                for(Images deImg:sku.getImages()){
                    if(deImg.getDefaultImg()==1){
                        defaultImage=deImg.getImgUrl();
                    }
                }
//                sku.getImages().stream().map(defaultImages -> {
//                    System.out.println(defaultImages.getDefaultImg() == 1);
//                    System.out.println(defaultImages.getDefaultImg());
//                    System.out.println(defaultImages.getImgUrl());
//                    if (defaultImages.getDefaultImg() == 1) {
//                        return defaultImages.getImgUrl().toString();
//                    }else{
//                        return null;
//                    }
//                }).toString();
                //5.1 sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();


                //5.2 sku图片信息 pms_sku_images
                //保存图片需要调用到skuId，所以此处循环写入在sku的保存方法中
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(skuImg -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(skuImg.getImgUrl());
                    skuImagesEntity.setDefaultImg(skuImg.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回 true 就是接收，返回false就是剔除
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);


                //5.3 sku的销售属性信息 pms_sku_sell_attr_value
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(sellAttr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sellAttr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
                //Todo
                //5.4 sku的优惠信息、满减信息;
                // sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
//                if(skuReductionTo.getFullCount()>0||
//                        skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){
                R result = couponFeignService.saveSkuReduction(skuReductionTo);
                if (result.getCode() == 0) {

                } else {
                    log.error("远程保存SPU满减信息错误");
                }
//                }

            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();

        String key = params.get("key").toString();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = params.get("status").toString();
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = params.get("brandId").toString();
        if (StringUtils.isNotEmpty(brandId)) {
            if (!brandId.equals("0")) {
                wrapper.eq("brand_id", brandId);
            }
        }

        String catelogId = params.get("catelogId").toString();
        if (StringUtils.isNotEmpty(catelogId)) {
            if (!catelogId.equals("0")) {
                wrapper.eq("catalog_id", catelogId);
            }
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void up(Long spuId) {
        List<SkuEsModel> upProducts = new ArrayList<>();
        //1、组装需要的数据
        SkuEsModel skuEsModel = new SkuEsModel();
        //1)当前spuId对应的所有Sku信息，品牌名字等
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getskusBySpuInfo(spuId);

        //检查当前Sku所有参与搜索的属性字段提取工作
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr->{
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //查出所有search_type为1的值
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> esAttrs = baseAttrs.stream().filter(item->{
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attrs esAttr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item,esAttr);
            return esAttr;
        }).collect(Collectors.toList());


        //2)封装每个sku信息
        Map<Long, Boolean> hasStockStatus = null;
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        try {
            R hasStock = wareFeignService.getSkuHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            hasStockStatus = hasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {

        }
        Map<Long, Boolean> finalHasStockStatus = hasStockStatus;

        upProducts = skuInfoEntities.stream().map(sku -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(sku, model);
            //price、img、stock、score、brandName、brandImg、catalogName
            model.setSkuPrice(sku.getPrice());
            model.setSkuImg(sku.getSkuDefaultImg());

            //远程查询库存信息，查询是否有库存信息


            //设置库存信息
            if (finalHasStockStatus == null) {
                model.setHasStock(true);
            } else {
                model.setHasStock(finalHasStockStatus.get(model.getSkuId()));
            }


            //设置热度
            model.setHotScore(0L);

            //查询品牌名字和分类名字并进行插入保存
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            model.setBrandName(brandEntity.getName());
            model.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            model.setCatalogName(categoryEntity.getName());

            //设置检索属性
            model.setAttrs(esAttrs);

            return model;
        }).collect(Collectors.toList());

        //发给es进行远程保存 gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            //调用成功
            //todo 6、当前上架状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //调用失败
            log.error("上架失败");
            //todo 重复调用上传（接口幂等性）
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        return getById(skuInfoEntity.getSpuId());
    }

}